在製作影像和逐幀處理一些視覺化的專案,時常會使用到OpenCV做影片的讀寫。以下提供圖片轉影像、影像轉影像的兩個寫法。
from pathlib import Path
import tqdm
import cv2
def set_camera(filename: str, width: int, height: int,
fps: float = 30.0, fourcc: str = 'mp4v') -> cv2.VideoWriter:
return cv2.VideoWriter(
filename,
fourcc=cv2.VideoWriter_fourcc(*fourcc),
fps=fps,
frameSize=(width, height)
)
batch_images = sorted(Path('path/to/batch/dir').glob('*.jpg'))
video_output_path = 'video.mp4'
camera = None
for ip in tqdm.tqdm(batch_images):
frame = cv2.imread(ip.as_posix())
# process ...
if camera is None:
h, w, _ = frame.shape
camera = set_camera(video_output_path, w, h)
camera.write(frame)
camera.release()
video = cv2.VideoCapture('path/to/video.mp4')
video_output_path = 'video.mp4'
camera = None
for i in tqdm.trange(int(video.get(7))):
_, frame = video.read()
# process ...
if camera is None:
h, w, _ = frame.shape
camera = set_camera(video_output_path, w, h)
camera.write(frame)
camera.release()